﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web;

namespace Com.CMS263.Util
{
   
    public class ImageUtil
    {

        #region 缩略照片
        /// <summary>
        /// 上传照片生成缩略图(ssc 08/09/08)
        /// </summary>
        /// <param name="filename">源图片文件名</param>
        /// <param name="originalImagePath">源图片路径,直接传递目录</param>
        /// <param name="thumbnailPath">处理后的图片路径,直接传递目录</param>
        /// <param name="width">图片宽度</param>
        /// <param name="height">图片高度</param>
        /// <param name="mode">图片裁剪方式("HW":指定高宽缩放(可能变形);"W":指定宽，高按比例;"H":指定高，宽按比例; "Cut":指定高宽裁减(不变形))</param>
        /// <param name="p">当前的page类</param>
        public void MakeThumbnail(string filename, string originalImagePath, string thumbnailPath, int width, int height, string mode)
        {

            if (!Directory.Exists(System.Web.HttpContext.Current.Server.MapPath(thumbnailPath)))
            {
                Directory.CreateDirectory(System.Web.HttpContext.Current.Server.MapPath(thumbnailPath));
            }
            originalImagePath = System.Web.HttpContext.Current.Server.MapPath(originalImagePath) + filename;
            thumbnailPath = System.Web.HttpContext.Current.Server.MapPath(thumbnailPath) + filename;

            System.Drawing.Image originalImage = System.Drawing.Image.FromFile(originalImagePath);

            int towidth = width;
            int toheight = height;

            int x = 0;
            int y = 0;
            int ow = originalImage.Width;
            int oh = originalImage.Height;

            switch (mode)
            {
                case "HW"://指定高宽缩放（可能变形） 
                    break;
                case "W"://指定宽，高按比例 
                    toheight = originalImage.Height * width / originalImage.Width;
                    break;
                case "H"://指定高，宽按比例 
                    towidth = originalImage.Width * height / originalImage.Height;
                    break;
                case "Cut"://指定高宽裁减（不变形） 
                    if ((double)originalImage.Width / (double)originalImage.Height > (double)towidth / (double)toheight)
                    {
                        oh = originalImage.Height;
                        ow = originalImage.Height * towidth / toheight;
                        y = 0;
                        x = (originalImage.Width - ow) / 2;
                    }
                    else
                    {
                        ow = originalImage.Width;
                        oh = originalImage.Width * height / towidth;
                        x = 0;
                        y = (originalImage.Height - oh) / 2;
                    }
                    break;
                default:
                    break;
            }

            //新建一个bmp图片 
            System.Drawing.Image bitmap = new System.Drawing.Bitmap(towidth, toheight);

            //新建一个画板 
            System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap);

            //设置高质量插值法 
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;

            //设置高质量,低速度呈现平滑程度 
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;

            //清空画布并以透明背景色填充 
            g.Clear(System.Drawing.Color.Transparent);

            //在指定位置并且按指定大小绘制原图片的指定部分 
            try
            {
                g.DrawImage(originalImage, new System.Drawing.Rectangle(0, 0, towidth, toheight),
                new System.Drawing.Rectangle(x, y, ow, oh),
                System.Drawing.GraphicsUnit.Pixel);
            }
            catch (Exception ee)
            {
                throw ee;
            }

            try
            {
                //以jpg格式保存缩略图 
                bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Jpeg);

            }
            catch (System.Exception e)
            {
                throw e;
            }
            finally
            {
                originalImage.Dispose();
                bitmap.Dispose();
                g.Dispose();
            }
        }
        #endregion


        #region 上传文件到指定路径
        /// <summary>
        /// 上传文件到指定路径
        /// </summary>
        /// <param name="name">FileUpload的名字</param>
        /// <param name="maxLength">文件的大小，以字节为单位(1024*1024=1MB)</param>
        /// <param name="webfilepath">指定上传文件目录,直接传递目录</param>
        /// <param name="fileType">上传文件类型,多个以"|"分隔开</param>
        /// <param name="p">页面的Page类</param>
        /// <returns></returns>
        public String uploadFile(FileUpload name, int maxLength, string webfilepath, string fileType, Page p)
        {
            string newfilename = "";
            if (name.HasFile)
            {
                string fileLast = name.PostedFile.FileName.ToLower().Split('.')[name.PostedFile.FileName.ToLower().Split('.').Length - 1];    //获取上传附件的后缀名
                bool isW = false;
                for (int i = 0; i < fileType.Split('|').Length; i++)
                {
                    if (fileLast == fileType.Split('|')[i].ToString())
                    {
                        isW = true;
                        break;
                    }
                }
                if (!isW)
                {

                    StringUtil.Alert("不允许上传此种文件类型", "-1", p);
                }
                if (name.PostedFile.ContentLength < 5)
                {
                    StringUtil.Alert("请选择文件，格式为" + fileType + "", "-1", p);
                }
                else if (name.PostedFile.ContentLength > maxLength)
                {
                    StringUtil.Alert("上传文件超过了最大限制", "-1", p);
                }
                else
                {

                    if (!Directory.Exists(p.Server.MapPath(webfilepath)))
                    {
                        Directory.CreateDirectory(p.Server.MapPath(webfilepath));
                    }
                    Random rnd = new Random();
                    int rndNum = rnd.Next(100, 200); //得100-200的随机数 
                    newfilename = DateTime.Now.ToString("yyyyMMddHHmmss") + rndNum + "." + fileLast; //生成新的图片名，数据库中对应
                    try
                    {
                        name.SaveAs(p.Server.MapPath(webfilepath) + newfilename);
                    }
                    catch (Exception e)
                    {
                        p.Response.Write(e);
                    }

                }

            }

            return newfilename;
        }
        #endregion


        #region 图片加水印
        /// <summary>
        /// 加图片水印
        /// </summary>
        /// <param name="filePath">要加水印的图片路径</param>
        /// <param name="markPath">水印图片路径</param>
        /// <param name="p">当前的page类</param>
        public void AddMark(string filePath, string markPath ,Page p)
        {
            filePath = p .Server.MapPath(filePath);
            //加文字水印，注意，这里的代码和以下加图片水印的代码不能共存
            System.Drawing.Image image = System.Drawing.Image.FromFile(filePath);
            //转换成位图文件
            Bitmap bm = new Bitmap(image.Width, image.Height);
            Graphics g = Graphics.FromImage(bm);
            g.DrawImage(image, 0, 0, image.Width, image.Height);

            //Font f = new Font("Verdana", 12, FontStyle.Bold);
            //SolidBrush b = new SolidBrush(Color.FromArgb(153, 0, 0, 0));
            //string addText = markText.Trim();


            System.Drawing.Image copyImage = System.Drawing.Image.FromFile(markPath);

            ImageAttributes imageAttributes = new ImageAttributes();
            ColorMap colorMap = new ColorMap();

            colorMap.OldColor = Color.FromArgb(255, 0, 255, 0);
            colorMap.NewColor = Color.FromArgb(0, 0, 0, 0);
            ColorMap[] remapTable = { colorMap };

            imageAttributes.SetRemapTable(remapTable, ColorAdjustType.Bitmap);

            float[][] colorMatrixElements = {
                                               new float[] {1.0f,  0.0f,  0.0f,  0.0f, 0.0f},
                                              new float[] {0.0f,  1.0f,  0.0f,  0.0f, 0.0f},
                                               new float[] {0.0f,  0.0f,  1.0f,  0.0f, 0.0f},
                                               new float[] {0.0f,  0.0f,  0.0f,  1.0f, 0.0f},
                                               new float[] {0.0f,  0.0f,  0.0f,  0.0f, 1.0f}
                                           };

            ColorMatrix colorMatrix = new ColorMatrix(colorMatrixElements);

            imageAttributes.SetColorMatrix(colorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);


            g.DrawImage(copyImage, new Rectangle(image.Width - copyImage.Width - 10, image.Height - copyImage.Height, copyImage.Width, copyImage.Height), 0, 0, copyImage.Width, copyImage.Height, GraphicsUnit.Pixel, imageAttributes);

            // g.DrawString(markText, f, b, l, t);
            //用位图保存图片

            FileInfo fi = new FileInfo(filePath);
            if (fi.Extension.Equals(".jpg", StringComparison.OrdinalIgnoreCase))
            {
                bm.Save(filePath + ".bak", ImageFormat.Jpeg);
            }
            else if (fi.Extension.Equals(".gif", StringComparison.OrdinalIgnoreCase))
            {
                bm.Save(filePath + ".bak", ImageFormat.Gif);
            }
            else if (fi.Extension.Equals(".bmp", StringComparison.OrdinalIgnoreCase))
            {
                bm.Save(filePath + ".bak", ImageFormat.Bmp);
            }
            else if (fi.Extension.Equals(".png", StringComparison.OrdinalIgnoreCase))
            {
                bm.Save(filePath + ".bak", ImageFormat.Png);
            }


            g.Dispose();

            ////加图片水印
            //System.Drawing.Image image = System.Drawing.Image.FromFile(path);
            //System.Drawing.Image copyImage = System.Drawing.Image.FromFile( Server.MapPath(".") + "/Alex.gif");
            //Graphics g = Graphics.FromImage(image);
            //g.DrawImage(copyImage, new Rectangle(image.Width-copyImage.Width, image.Height-copyImage.Height, copyImage.Width, copyImage.Height), 0, 0, copyImage.Width, copyImage.Height, GraphicsUnit.Pixel);
            //g.Dispose();

            //删除原始图片,保存加水印过后的图片

            bm.Dispose();
            image.Dispose();
            if (File.Exists(filePath))
            {
                File.Delete(filePath);
            }



            File.Copy(filePath + ".bak", filePath);
            File.Delete(filePath + ".bak");
        }
        #endregion


        #region 非控件上传文件到指定路径
        /// <summary>
        /// 非控件上传文件到指定路径
        /// </summary>
        /// <param name="name">FileUpload的名字</param>
        /// <param name="maxLength">文件的大小，以字节为单位(1024*1024=1MB)</param>
        /// <param name="webfilepath">指定上传文件目录,直接传递目录</param>
        /// <param name="fileType">上传文件类型,多个以"|"分隔开</param>
        /// <param name="p">页面的Page类</param>
        /// <returns></returns>
        public String UpFile(HttpPostedFileBase name, int maxLength, string webfilepath, string fileType)
        {
            string newfilename = "";

            if (name.ContentLength > 5)
            {
                string fileLast = name.FileName.ToLower().Split('.')[name.FileName.ToLower().Split('.').Length - 1];    //获取上传附件的后缀名
                bool isW = false;
                for (int i = 0; i < fileType.Split('|').Length; i++)
                {
                    if (fileLast == fileType.Split('|')[i].ToString())
                    {
                        isW = true;
                        break;
                    }
                }
                if (!isW)
                {

                    StringUtil.Alert("不允许上传此种文件类型", "-1");
                }
                if (name.ContentLength < 5)
                {
                    StringUtil.Alert("请选择文件，格式为" + fileType + "", "-1");
                }
                else if (name.ContentLength > maxLength)
                {
                    StringUtil.Alert("上传文件超过了最大限制", "-1");
                }
                else
                {

                    if (!Directory.Exists(System.Web.HttpContext.Current.Server.MapPath(webfilepath)))
                    {
                        Directory.CreateDirectory(System.Web.HttpContext.Current.Server.MapPath(webfilepath));
                    }
                    Random rnd = new Random();
                    int rndNum = rnd.Next(100, 200); //得100-200的随机数 
                    newfilename = DateTime.Now.ToString("yyyyMMddHHmmss") + rndNum + "." + fileLast; //生成新的图片名，数据库中对应
                    try
                    {
                        name.SaveAs(System.Web.HttpContext.Current.Server.MapPath(webfilepath) + newfilename);
                    }
                    catch (Exception e)
                    {
                        System.Web.HttpContext.Current.Response.Write(e);
                    }

                }

            }
            return newfilename;

        }
        #endregion

    }
}
